package com.fxsh168.server.maps;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.trace.OnEntityListener;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnStopTraceListener;
import com.baidu.trace.TraceLocation;
import com.fxsh168.server.R;
import com.fxsh168.server.activity.AboutUserActivity;
import com.fxsh168.server.activity.MainActivity;
import com.fxsh168.server.base.BaseActivity;
import com.fxsh168.server.entitys.PushOrdersEntity;
import com.fxsh168.server.entitys.WanChen;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.maps.yinyan.DateUtils;
import com.fxsh168.server.maps.yinyan.MonitorService;
import com.fxsh168.server.maps.yinyan.TrackReceiver;
import com.fxsh168.server.otherviews.banner.MyApplication;
import com.fxsh168.server.services.QueryDistanceService;
import com.fxsh168.server.utils.PopInfo;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import okhttp3.Call;

public class NavQian extends BaseActivity implements View.OnClickListener, OnGetSuggestionResultListener, OnGetRoutePlanResultListener {
    private Button mBtnStartNav, mWanchengdingdan;
    private MapView mMapView;
    private BaiduMap mBaiduMap;

    //定位相关
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private boolean isFirstIn = true;
    //记录下当前定位的经纬度
    private double mLatitude, mLongitude;
    //自定义定位图标
//    private BitmapDescriptor mIconLocation;
    //导航相关
    public static List<Activity> activityList = new LinkedList<Activity>();
    private static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";
    private String mSDCardPath = null;
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private final static String authBaseArr[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private final static int authBaseRequestCode = 1, authComRequestCode = 2;
    private boolean hasInitSuccess = false, hasRequestComAuth = false;
    private BDLocation mSLocation;
    double cslatitude, cslongitude, celatitudel, celongitudel;
    Double adaslatitude, adaslongitude, adaelatitudel, adaelongitudel;
    String actoininit, action = null;
    private List<PushOrdersEntity.DataBean> dataAda;
    int positionAda, curPosition, loca = 0;
    private List<PushOrdersEntity.DataBean> dataed;
    //线路规划相关
    private SuggestionSearch suggestionSearch;
    private RoutePlanSearch mSearch;
    private LatLng curLatLng;
    private int nodeIndex = -1;//节点索引，供浏览节点时使用
    private RouteLine route = null;
    TextView popupText;
    LatLng curloclatLng;//司机自己的位置
    private String mPhone, token, cid, adaid;
    double sendSumDistance;   // 距离
    PopInfo popInfo;
    RelativeLayout reShow;
    ImageButton ib_return;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        activityList.add(this);
        setContentView(R.layout.activity_nav_qian);
        SharedPreferences sp = getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        mPhone = sp.getString("mPhone", "");
        token = sp.getString("token", "");
        reShow = (RelativeLayout) findViewById(R.id.reShow);
        mBtnStartNav = (Button) findViewById(R.id.btnStartNav);
        mWanchengdingdan = (Button) findViewById(R.id.wanchengdingdan);
        ib_return = (ImageButton) findViewById(R.id.ib_return);
        mBtnStartNav.setOnClickListener(this);
        mWanchengdingdan.setOnClickListener(this);
        mMapView = (MapView) findViewById(R.id.id_bmapView2);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //设置精度为500米左右
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        //初始化定位
        initLocation();
        BNOuterLogUtil.setLogSwitcher(true);
        suggestionSearch = SuggestionSearch.newInstance();
        suggestionSearch.setOnGetSuggestionResultListener(this);
        //初始化搜索模块，注册监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        getDataPC();     //乘客已上车
        //初始化导航
        if (initDirs()) {
            initNavi();
        }
        if (action != null && action.equals("PassAdapter")) {
            initListener(action);
        } else {
            initListener(action);
            ib_return.setVisibility(View.INVISIBLE);
        }
    }


    //导航
    public void initListener(final String actoinin) {
        if (mBtnStartNav != null) {
            mBtnStartNav.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (BaiduNaviManager.isNaviInited()) {
//                        trackApp.getClient().onDestroy();
                        actoininit = actoinin;
                        routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL, actoinin);
                    }
                }
            });
        }
    }

    //通过序列化传过来的总的值
    public void getDataPC() {
        Intent intent = getIntent();
        action = intent.getAction().trim();
        String biao = intent.getStringExtra("biao");
        curPosition = intent.getIntExtra("CurPosition", -1);
        switch (action) {
            case "btnRouteSchedul":    //乘PLACED客上车
                if (biao == null) {
                    playVoce(2, NavQian.this);
                    mBtnStartNav.setText("开始导航");
                } else {
                    mBtnStartNav.setText("继续导航");
                }

                PushOrdersEntity pushOrdersEntity2 = (PushOrdersEntity) intent.getSerializableExtra("pushOrdersEntity2");
                if (pushOrdersEntity2 != null && !TextUtils.isEmpty(pushOrdersEntity2.toString().trim())) {
                    dataed = pushOrdersEntity2.getData();
                    if (!TextUtils.isEmpty(dataed.toString().trim()) && dataed != null && dataed.size() > 0) {
                        for (int i = 0; i < dataed.size(); i++) {
                            loca = dataed.size();
                            PushOrdersEntity.DataBean dataBean = dataed.get(i);
                            String clatitude = dataBean.getLatitude().toString().trim();
                            String clongitude = dataBean.getLongitude().toString().trim();
                            String clatitudel = dataBean.getLatitudel().toString().trim();
                            String clongitudel = dataBean.getLongitudel().toString().trim();

                            cid = dataBean.getId().toString().trim();
                            cslatitude = Double.valueOf(clatitude);
                            cslongitude = Double.valueOf(clongitude);
                            celatitudel = Double.valueOf(clatitudel);
                            celongitudel = Double.valueOf(clongitudel);
                            mWanchengdingdan.setVisibility(View.VISIBLE);
                            Log.e("tag", "导航界面坐标确认" + clatitude + "+" + clongitude + "+" + clatitudel + "+" + clongitudel + "转化后" + cslatitude + "==" + cslongitude + "==" + celatitudel + "==" + celongitudel);
                        }
                    }
                }
                break;
            case "PassAdapter":   //接乘客
                String adalatitude = intent.getStringExtra("adalatitude").trim();
                String adalongitude = intent.getStringExtra("adalongitude").trim();
                String adalatitudel = intent.getStringExtra("adalatitudel").trim();
                String adalongitudel = intent.getStringExtra("adalongitudel").trim();
                PushOrdersEntity pushOrdersEntity = (PushOrdersEntity) intent.getSerializableExtra("pushOrdersEntity");
                positionAda = intent.getIntExtra("position", 0);
                dataAda = pushOrdersEntity.getData();
                adaslatitude = Double.valueOf(adalatitude);
                adaslongitude = Double.valueOf(adalongitude);
                adaelatitudel = Double.valueOf(adalatitudel);
                adaelongitudel = Double.valueOf(adalongitudel);
                adaid = intent.getStringExtra("id");
                mWanchengdingdan.setVisibility(View.INVISIBLE);
                break;
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.wanchengdingdan:
//                stopTrace();
                stopService(new Intent(NavQian.this, QueryDistanceService.class));
                SharedPreferences sp = getSharedPreferences(Constant.PLACED, MODE_PRIVATE);
                String ds = sp.getString("mDistance", "0");
                Log.e("tag", "完成数据库距离打印" + ds + "//////");
                wangChengDD(ds);
                break;
        }
    }

    //完成订单后提交
    private void wangChengDD(String ds) {
        OkHttpUtils.post().addParams("phone", mPhone).addParams("token", token)
                .addParams("id", cid)
//                .addParams("distance", sendSumDistance + "")   //线路规划的距离
                .addParams("distance", ds)          //获取到的实际距离
                .url(Constant.WANCHENGDDREQUESTPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    Log.e("tag", "完成订单语音输出" + response);
                    WanChen wanChen = new Gson().fromJson(response, WanChen.class);
                    String code = wanChen.getCode();
                    if (code.equals(200 + "")) {
                        SharedPreferences sp = NavQian.this.getSharedPreferences(Constant.PLACED, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("mDistance","0");
                        editor.putBoolean("finish",true);
                        editor.commit();       //提交清空数据库
                        playVoce(1, NavQian.this);   //播放声音
                        String teShow = "订单已完成";
                        popInfo = new PopInfo(NavQian.this, reShow, teShow, clickShow);
                    } else if (code.equals(203 + "")) {
                        showToast("失败!");
                    }
                }
            }
        });
    }

    //       点击跳转评价
    private View.OnClickListener clickShow = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(NavQian.this, AboutUserActivity.class);
            intent.putExtra("ids", cid);
            startActivity(intent);
            finish();
        }
    };


    public void initLocation() {
        mLocationClient = new LocationClient(this);
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        //设置定位请求
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//定位模式为高精度
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
//        mLocationClient.start();
        //初始化图标
//        mIconLocation = BitmapDescriptorFactory.fromResource(R.mipmap.akhsd);
        centerToMyLocation();
    }

    //设置进页面的时候就定位到自己位置
    private void centerToMyLocation() {
        //当点击定位到我的位置的时候让地图定位到我的位置
        curLatLng = new LatLng(mLatitude, mLongitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(curLatLng);
        mBaiduMap.animateMapStatus(msu);
    }

    //发起线路规划搜索示例
    public void SearchProcess(double latitudesLoca, double longitudesLoca) {
        route = null;
        double latitudes = latitudesLoca;
        double longitudes = longitudesLoca;
        double realslatitudes = 0.0;
        double realslongitudes = 0.0;
        double realelatitudes = 0.0;
        double realelongitudes = 0.0;
        //必须要把乘客先接了才进行总的线路规划
        if (action.equals("PassAdapter")) {
            if (dataAda != null && !TextUtils.isEmpty(dataAda.toString().trim())) {
                realslatitudes = latitudes;
                realslongitudes = longitudes;
                realelatitudes = adaslatitude;
                realelongitudes = adaslongitude;
            }
        } else if (action.equals("btnRouteSchedul")) {
            if (dataed != null && !TextUtils.isEmpty(dataed.toString().trim())) {
                realslatitudes = latitudes;
                realslongitudes = longitudes;
                realelatitudes = celatitudel;
                realelongitudes = celongitudel;
            }
        }
        if (!TextUtils.isEmpty(realslatitudes + "") && !TextUtils.isEmpty(realslongitudes + "") && !TextUtils.isEmpty(realelatitudes + "") && !TextUtils.isEmpty(realelongitudes + "")) {
            LatLng slatLngs = new LatLng(realslatitudes, realslongitudes);
            LatLng elatLngs = new LatLng(realelatitudes, realelongitudes);
            PlanNode stNode = PlanNode.withLocation(slatLngs);//自己的起点
            PlanNode enNode = PlanNode.withLocation(elatLngs);//终点
            //实际使用中请对起点终点城市进行正确的设定
            mSearch.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(enNode));
            nodeClick();
        } else {
            Log.e("shuju", "经纬度不全");
        }
    }

    //节点浏览示例
    public void nodeClick() {
        if (route == null || route.getAllStep() == null) {
            return;
        }
        //获取节点结果信息
        LatLng nodeLocation = null;
        String nodeTitle = null;

        Object step = route.getAllStep().get(nodeIndex);
        if (step instanceof DrivingRouteLine.DrivingStep) {
            nodeLocation = ((DrivingRouteLine.DrivingStep) step).getEntrace().getLocation();
            nodeTitle = ((DrivingRouteLine.DrivingStep) step).getInstructions();// 节点行驶路线
        }
        if (nodeLocation == null || nodeTitle == null) {
            return;
        }

        // 移动节点至中心
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
        // show popup
        popupText = new TextView(NavQian.this);
        popupText.setBackgroundResource(R.drawable.popup);
        popupText.setTextColor(0xFF000000);
        popupText.setText(nodeTitle);
        mBaiduMap.showInfoWindow(new InfoWindow(popupText, nodeLocation, 0));
    }

    //
    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
            return;
        }
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }


    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
        if (drivingRouteResult == null || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(NavQian.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起点终点或途经点地址有歧义，通过以下接口获取建议查询信息
            List<CityInfo> list = drivingRouteResult.getSuggestAddrInfo().getSuggestEndCity();
            return;
        }
        if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            List<Double> SumDistanceLists = null;
            List<DrivingRouteLine> routeLines = drivingRouteResult.getRouteLines();
            if (routeLines.size() > 0) {
                SumDistanceLists = new ArrayList<>();
                for (int i = 0; i < routeLines.size(); i++) {
                    DrivingRouteLine drivingRouteLine = routeLines.get(i);
                    if (drivingRouteLine != null) {
                        List<DrivingRouteLine.DrivingStep> allStep = drivingRouteLine.getAllStep();
                        double SumDistance = 0;
                        if (allStep.size() > 0) {
                            for (int j = 0; j < allStep.size(); j++) {
                                int distance = allStep.get(j).getDistance();
                                double discur = distance;
                                SumDistance += discur;
                            }
                        }
                        SumDistanceLists.add(SumDistance);
                    }
                }
            }

            //获取最小值
            int iCur = 0;
            double min = SumDistanceLists.get(0);
            for (int i2 = 0; i2 < SumDistanceLists.size(); i2++) {
                if (SumDistanceLists.get(i2) < min) {
                    min = SumDistanceLists.get(i2);
                    iCur = i2;
                }
            }
            //上传距离
            sendSumDistance = min / 1000;
            route = routeLines.get(iCur);
            MyDrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(routeLines.get(iCur));
            overlay.addToMap();
            overlay.zoomToSpan();
        }
    }


    //定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {
        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
//            if (useDefaultIcon) {
//                return BitmapDescriptorFactory.fromResource(R.mipmap.start);
//            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
//            if (useDefaultIcon) {
//                return BitmapDescriptorFactory.fromResource(R.mipmap.end);
//            }
            return null;
        }
    }

    //定位SDK监听函数
    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            MyLocationData data = new MyLocationData.Builder()
                    .accuracy(location.getRadius())//精度
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(data);
            //设置到自定义图标
//            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration
//                    .LocationMode.NORMAL, true, null);
//            mBaiduMap.setMyLocationConfigeration(config);
            //每次定位成功进行更新
            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            Log.e("LALon", "mLatitude=" + mLatitude + ",mLongitude=" + mLongitude);
            if (isFirstIn) {
                SearchProcess(mLatitude, mLongitude);
                curloclatLng = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(curloclatLng);
                mBaiduMap.animateMapStatus(msu);
                isFirstIn = false;
                //获得当前定位的位置
                mSLocation = location;
            }
        }

    }


    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    String authinfo = null;
    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };
    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {

        }

        @Override
        public void playStart() {

        }
    };


    private boolean hasBasePhoneAuth() {
        PackageManager pm = this.getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private boolean hasCompletePhoneAuth() {
        PackageManager pm = this.getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, this.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void initNavi() {
        BNOuterTTSPlayerCallback ttsCallback = null;

        // 申请权限
        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {
                this.requestPermissions(authBaseArr, authBaseRequestCode);
                return;
            }
        }
        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
                    authinfo = "key校验成功!";

                } else {
                    authinfo = "key校验失败, " + msg;
                }
                NavQian.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(NavQian.this, authinfo, Toast.LENGTH_LONG).show();
                        Log.e("tag", "key校验" + authinfo);
                    }
                });
            }

            public void initSuccess() {
                Toast.makeText(NavQian.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                hasInitSuccess = true;
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(NavQian.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
                Toast.makeText(NavQian.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }

        }, null, ttsHandler, ttsPlayStateListener);

    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private BNRoutePlanNode.CoordinateType mCoordinateType = null;

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType, String actionro) {
        mCoordinateType = coType;
        if (!hasInitSuccess) {
            Log.e("tag", "还未初始化!");
        }
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    this.requestPermissions(authComArr, authComRequestCode);
                    return;
                }
            }

        }
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        double latitude = mSLocation.getLatitude();
        double longitude = mSLocation.getLongitude();
        double realslatitude = 0.0;
        double realslongitude = 0.0;
        double realelatitude = 0.0;
        double realelongitude = 0.0;
        //必须要把乘客先接了才进行总的线路规划
        if (actionro.equals("PassAdapter")) {
            if (dataAda != null && !TextUtils.isEmpty(dataAda.toString().trim())) {
                realslatitude = latitude;
                realslongitude = longitude;
                realelatitude = adaslatitude;
                realelongitude = adaslongitude;
            }
        } else if (actionro.equals("btnRouteSchedul")) {
            if (dataed != null && !TextUtils.isEmpty(dataed.toString().trim())) {
                realslatitude = latitude;
                realslongitude = longitude;
                realelatitude = celatitudel;
                realelongitude = celongitudel;
            }
        }
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(realslongitude, realslatitude, "我的地点", null, coType);
                eNode = new BNRoutePlanNode(realelongitude, realelatitude, "目的地", null, coType);
                break;
            }
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }


    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {
        private BNRoutePlanNode mBNRoutePlanNode = null;

        DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
//             * 设置途径点以及resetEndNode会回调该接口
            for (Activity ac : activityList) {
                if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {
                    return;
                }
            }
            Intent intent = new Intent(NavQian.this, BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("cid", cid);
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.setAction(action);
            startActivityForResult(intent, 66);
        }

        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(NavQian.this, "距离太近了!", Toast.LENGTH_SHORT).show();
        }
    }

    private void initSetting() {
        // BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    private BNOuterTTSPlayerCallback mTTSCallback = new BNOuterTTSPlayerCallback() {

        @Override
        public void stopTTS() {

        }

        @Override
        public void resumeTTS() {

        }

        @Override
        public void releaseTTSPlayer() {

        }

        @Override
        public int playTTSText(String speech, int bPreempt) {

            return 1;
        }

        @Override
        public void phoneHangUp() {

        }

        @Override
        public void phoneCalling() {

        }

        @Override
        public void pauseTTS() {

        }

        @Override
        public void initTTSPlayer() {

        }

        @Override
        public int getTTSState() {

            return 1;
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == authBaseRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                } else {
                    Toast.makeText(NavQian.this, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            initNavi();
        } else if (requestCode == authComRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                }
            }
            routeplanToNavi(mCoordinateType, actoininit);
        }
    }

    @Override
    public void onStart() {
        //开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        super.onStart();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onStop() {
        //停止方向传感器
        mLocationClient.stop();
        //停止定位
        mBaiduMap.setMyLocationEnabled(false);
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        mSearch.destroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        suggestionSearch.destroy();
        mMapView.onDestroy();
        super.onDestroy();
    }

}
